import {useState,useEffect} from "react";
import style from "./region.module.scss";

import {region} from "../../common/data/_region";

const RegionLeveChose = (props)=>{
    const [location,setLocation] = useState({
        cityList:[],
        flag:false,
        province:"",
        city:"",
        area:"",
        address:"",
    });

 useEffect(()=>{
    //  console.log("location",location);
 },[location]);

 let regionItems = region.map((it,i)=>{
    return <option key={i} value={i}>{it.name}</option>
 });

 return (
   <div className={style["region-root"]}>
       <span className={style["tag"]}
         onClick={()=>{
            let locationNext = {...location};
            locationNext.flag = true;
            setLocation(locationNext);
         }}
       >{location.address || props.placeholder}</span>

       <div className={style["leve-bg"]} style={location.flag ? {top:"0"}:null}>
           <div>
               <select onChange={(e)=>{
                     let taget = region[e.target.value];
                     let cityListItems = [];
                     if(taget && taget.children){
                         cityListItems = taget.children.map((it,i)=>{
                            return <option key={it.id} value={i}>{it.name}</option>
                         });
                     }
                     
                     let locationNext = {...location};
                     locationNext.province = e.target.value;
                     locationNext.cityList = cityListItems;
                     setLocation(locationNext);
                }}
               >
                   <option key={-1} value={-1}>--请选择--</option>
                    {regionItems}
               </select>
               <select onChange={(ev)=>{
                        ev.preventDefault();
                        let locationNext = {...location};
                        locationNext.city = ev.target.value;
                        locationNext.flag = false;
                        
                        
                        let {province, city} = locationNext;
                        let children = region[province].children;
                        let address = {
                            province:region[province].name,
                            city:children[city]?children[city].name:"",
                        }

                        let addressStr = address.province + "，" + address.city;
                        locationNext.address = addressStr;
                        setLocation(locationNext);

                        if(props.change && city >= 0){
                            props.change(address);
                        };
                    }}
               >
                   <option key={-1} value={-1}>--请选择--</option>
                   {location.cityList}
                </select>
           </div>
       </div>
    </div>
 )
}

export default RegionLeveChose